package cn.zz.veggie.application.service;

import java.util.List;

import org.springframework.stereotype.Service;

import cn.zz.comm.core.types.query.PageQuery;
import cn.zz.comm.helper.BizCommHelper;
import cn.zz.comm.types.IdNameObj;
import cn.zz.comm.types.result.P;
import cn.zz.comm.util.CollectorUtil;
import cn.zz.veggie.application.assembler.UserAssembler;
import cn.zz.veggie.application.packer.UserPacker;
import cn.zz.veggie.model.domain.User;
import cn.zz.veggie.model.query.UserQuery;
import cn.zz.veggie.persistence.repository.UserRepository;
import cn.zz.veggie.web.types.dto.mgmt.user.MgmtUserSaveDto;
import cn.zz.veggie.web.types.dto.my.MyLoginDTO;
import cn.zz.veggie.web.types.vo.LoginTokenVo;
import cn.zz.veggie.web.types.vo.mgmt.MgmtUserBriefVo;
import cn.zz.veggie.web.types.vo.mgmt.user.MgmtUserVo;
import lombok.RequiredArgsConstructor;

/**
 * @author zhongq
 * @since 2024/03/20
 */
@Service
@RequiredArgsConstructor
public class UserAppService {

	private final UserRepository userRepository;

	public LoginTokenVo accountLogin(MyLoginDTO dto) {
		// final User user = userRepository.findByUsername(dto.getUsername());
		// UserHelper.requireCheckLogin(user, dto.getPassword());
		// // create token
		// String token = userRepository.loginToken(user);
		return new LoginTokenVo(null);
	}

	public List<IdNameObj<Integer>> adminInputSearch(String keyword) {
		final UserQuery userQuery = UserQuery.ofLikeUsername(keyword);
		final PageQuery pageQuery = PageQuery.all().setSearchCount(false);
		final List<User> users = userRepository.findByPage(userQuery, pageQuery);
		return CollectorUtil.bwl(users, u -> new IdNameObj<>(u.getId(), u.getUsername()));
	}

	public MgmtUserBriefVo adminGetUserInfo(Integer uid) {
		final User user = userRepository.findById(uid);
		BizCommHelper.requireNoNull(user, uid.toString());
		return UserPacker.toMgmtUserBriefVo(user);
	}

	public P<MgmtUserVo> adminGetList(String keyword, PageQuery pageQuery) {
		final UserQuery query = new UserQuery();
		query.setLikeUsername(keyword);
		final List<User> users = userRepository.findByPage(query, pageQuery);
		List<MgmtUserVo> vos = CollectorUtil.bwl(users, UserPacker::toMgmtUserVo);
		return P.of(pageQuery, vos);
	}

	public void adminSaveUser(MgmtUserSaveDto dto) {
		User user = UserAssembler.buildUserSave(dto);
		userRepository.save(user);
	}
}